/**
 * Created by Adam on 2017/5/18.
 */
import React from 'react'
import { connect } from 'react-redux'
import { browserHistory } from 'react-router'
import { setRedirectUrl } from '../actions'

class EnsureLoggedInContainer extends React.Component {
    componentDidMount() {
        const { dispatch, currentUrl, isLoggedIn, redirectUrl } = this.props
        if (!isLoggedIn) {
            dispatch(setRedirectUrl(currentUrl))
            browserHistory.push("/login")
        } else {
            if (redirectUrl) {
                browserHistory.push(redirectUrl)
            }
        }
    }

    render() {
        const { dispatch, currentUrl, isLoggedIn } = this.props
        if (isLoggedIn) {
            return this.props.children
        } else {
            return null
        }
    }
}

const mapStateToProps = (state, ownProps) => {
    return {
        isLoggedIn: state.loginInfo.isLoggedIn,
        currentUrl: ownProps.location.pathname,
        redirectUrl: state.loginInfo.redirectUrl
    }
}

export default connect(mapStateToProps)(EnsureLoggedInContainer)